﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.EntityClient;
using System.Transactions;
using System.Data.Common;
using System.Data.Objects;

namespace ASPItalia.ModelVirtualCasting.EntityFramework.Wrappers {
	public class ContextWrapper : IContextWrapper, IDisposable{
		ModelVirtualCastingEntities _context;

		public ContextWrapper(ModelVirtualCastingEntities context) {
			_context = context;
		}
		
		public void ChangeObjectState(object entity, System.Data.EntityState state) {
			_context.ObjectStateManager.GetObjectStateEntry(entity).ChangeState(state);
		}

		public void SaveChanges(List<EntityCommand> commands, bool createNewContextAfterSaveChanges) {
			if (commands.Any()) {
				using (TransactionScope scope = new TransactionScope()) {
					_context.Connection.Open();
					commands.ForEach(c => {
						c.Connection = (EntityConnection)_context.Connection;
						c.ExecuteNonQuery();
					});
					_context.SaveChanges();
					scope.Complete();
				}
			}
			else {
				_context.SaveChanges();
			}
			if (createNewContextAfterSaveChanges)
				_context = new ModelVirtualCastingEntities(Configuration.ConnectionString);
		}

		public bool EnableLazyLoading {
			get {
				return _context.ContextOptions.LazyLoadingEnabled;
			}
			set {
				_context.ContextOptions.LazyLoadingEnabled = value;
			}
		}

		public ObjectSet<T> CreateObjectSet<T>() where T : class {
			return _context.CreateObjectSet<T>();
		}

		public void Dispose() {
			_context.Dispose();
		}
	}
}
